package com.example.bbgds.test.home.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.bbgds.test.R;
import com.example.bbgds.test.home.controller.DateTimeController;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * Created by zjzhu on 26/4/16.
 */
public class MainWidgetView extends RelativeLayout implements DateTimeController.DateTimeChangeCallback {

    private TextView mWeekView, mDateView;
    private String[] mWeekArrayStr = null;
    private SimpleDateFormat mDateFormat = null;

    public MainWidgetView(Context context) {
        this(context, null);
    }

    public MainWidgetView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MainWidgetView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void onFinishInflate() {
        super.onFinishInflate();
        mWeekArrayStr = getResources().getStringArray(R.array.week_name);
        mDateFormat = new SimpleDateFormat(getResources().getString(R.string.mainwidget_date_format));
        mWeekView = (TextView) findViewById(R.id.week);
        mDateView = (TextView) findViewById(R.id.date);
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        DateTimeController.getInstance(getContext()).addStateChangedCallback(this);
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        DateTimeController.getInstance(getContext()).removeStateChangedCallback(this);
    }

    @Override
    public void onDateTimeChanged(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        String week = "";
        int way = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (way >= 0 && way < mWeekArrayStr.length) {
            week = mWeekArrayStr[way];
        }
        mWeekView.setText(week);
        mDateView.setText(mDateFormat.format(date));
    }
}
